package controller;

import com.github.pagehelper.PageInfo;
import entity.Admin;
import entity.LayRequest;
import entity.MyResult;
import entity.Role;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import service.AdminService;
import service.RoleService;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @RequestMapping("/toAdd")
    public String toAdd(ModelMap modelMap){
        //查询所有的角色信息
        List<Role> roles=roleService.selectAll();
        //将角色信息返回到前台页面
        modelMap.addAttribute("roles",roles);
        return "add.jsp";
    }
    //method指定http的请求方式
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(Admin admin){
        boolean flag=adminService.insert(admin);
        return "redirect:list";
    }

//    @RequestParam用来获取前台传递的值，如果指定name属性，那么只获取对应的name的数据，但如果没有指定则获取所有的
    @RequestMapping("/list")
    public String list(@RequestParam Map<String,Object> map, ModelMap modelMap){
        //执行分页查询
        PageInfo<Admin> pageInfo=adminService.selectByPage(map);
        //将分页查询结果传递到页面
        modelMap.addAttribute("page",pageInfo);
        //回传查询条件
        modelMap.addAttribute("params",map);
        return "list.jsp";
    }

    @ResponseBody
    @RequestMapping("/laylist")
    public MyResult<List<Admin>> layList(LayRequest layRequest, ModelMap modelMap){
        //执行分页查询
        PageInfo<Admin> pageInfo=adminService.selectByPage(layRequest);
        return new MyResult<>(0,pageInfo.getList(),pageInfo.getTotal());
    }

//    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    @ResponseBody//返回json数据,会将返回的对象转化成json格式
    @GetMapping("/delete")
    public MyResult delete(Integer id){
        boolean flag=adminService.delete(id);
        return flag?new MyResult(200,"删除成功!"):new MyResult(500,"删除失败!");
    }

    @PostMapping("/login")
    public String login(String account, String password, HttpSession session){
        //根据用户名重新是否存在该用户
        Admin admin=adminService.selectByAccount(account);
        if (admin!=null&&admin.getPassword().equals(password)){
            //将用户信息放入session
            session.setAttribute("admin",admin);
            //查询用户拥有的菜单
            Role role =roleService.selectById(admin.getRoleid());
            //将角色和权限信息存放在session域中
            session.setAttribute("role",role);
            return "redirect:/index.jsp";//跳转到首页
        }
        return "/login.jsp";//以/开头为绝对路径,对应webapp目录
    }
    //MultipartFile 对象来接收上传的文件，参数名与input的name一致
    @PostMapping("/headpic")
    public String headPic(MultipartFile headpic,@RequestParam(required = false) Admin admin,Integer id) throws IOException {
        String filename=headpic.getOriginalFilename();
        System.out.println("上传的文件名："+filename);
        File file=new File("D:/upload/"+filename);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();//如果父目录不存在，创建该目录
        }
        //保存文件,将上传的文件内容写入file
        headpic.transferTo(file);
        admin=new Admin(id);
        //将头像路径保存到对象中
        admin.setHeadpic("/head/"+filename);
        //更新用户头像信息
        adminService.updateHeadPic(admin);
        return "redirect:list";
    }
    @GetMapping("/headpicDownload")
    public ResponseEntity<byte[]> headPicDownload(String filename) throws IOException {
        //1，定位到文件地址
        File file=new File("D:/upload/"+filename);
        //2,读取文件内容
        byte[] bytes= FileUtils.readFileToByteArray(file);
        //3,设置http响应头
        HttpHeaders headers=new HttpHeaders();
        //设置ContentType为Stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置以附件形式打开
        headers.setContentDispositionFormData("attachment",filename);
        //                                内容，头部信息   http状态码
        return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED);
    }
}
